package com.ljd.gulimall.search.Service.impl;

import com.alibaba.fastjson.JSON;
import com.ljd.common.to.es.SkuEsModel;
import com.ljd.gulimall.search.Service.ProductSaveService;
import com.ljd.gulimall.search.config.ElasticSearchConfig;
import com.ljd.gulimall.search.constant.EsConstant;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author 23817
 * @Date 19:41 2023/2/28
 * @Version 1.0
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        // 创建检索映射文件，指定索引 ,已在kibana创建
        // 批量保存sku信息到es
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            String jsonString = JSON.toJSONString(model);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        // 执行保存
        BulkResponse response = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        boolean failures = response.hasFailures();
        List<BulkItemResponse> collect = Arrays.stream(response.getItems()).peek(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品上架完成{}",collect);
        return failures;
    }
}
